import {init,h} from 'snabbdom'
import classModule from 'snabbdom/modules/class'
import propsModule from 'snabbdom/modules/props'
import styleModule from 'snabbdom/modules/style'
import eventListenersModule from 'snabbdom/modules/eventlisteners'

var patch = init([classModule, propsModule, styleModule, eventListenersModule]);
var container = document.getElementById("container");

// 定义数据
var data = ["1", "2", "3", "4", "5", "6", "7"];

// list-item
var item = function (itemIdx, itemData) {
  return h("li", {}, [
    itemData,
    h(
      "span", 
      
      {
        style: {
          color: "red",
          float: "right",
        },
        on: { click: [delEventHandler, itemIdx] },
      },
      ["del"]
    ),
  ]);
};

// list
var list = function () {
  let items = [];
  for (let i = 0; i < data.length; i++) {
    items.push(item(i, data[i]));
  }
  return h("ul", {}, items);
};

// btns
var btns = function () {
  return h("div", { style: { float: "right" } }, [
    h(
      "button",
      {
        on: {
          click: addEventHandler,
        },
      },
      "add"
    ),
    h(
      "button",
      {
        style: {
          marginLeft: "10px",
        },
        on: {
          click: reverseEventHandler,
        },
      },
      "reverse"
    ),
  ]);
};

// clearBoth
var clear = h("div", { style: { clear: "both" } });

// 主节点
var pageNode = function () {
  return h(
    "div#main",
    {
      style: {
        width: "800px",
        paddingTop: "30px",
        margin: "0 auto",
      },
    },
    [btns(), clear, list()]
  );
};

// 首次渲染保存当前节点为老节点
var oldPageNode = patch(container, pageNode());

// 刷新节点，并重新保存老节点
function updateNode() {
  oldPageNode = patch(oldPageNode, pageNode());
}

// 删除元素
function delEventHandler(idx) {
  data.splice(idx, 1);

  updateNode();
}

// 添加元素
function addEventHandler() {
  data.push("这是新增加的元素，随机数：" + Math.floor(Math.random() * 900 + 100));

  updateNode();
}

// 反转元素
function reverseEventHandler() {
  data.reverse();

  updateNode();
}


